using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using JGSY.CMS.LowCode.Platform.Infrastructure.Configuration;
using JGSY.CMS.LowCode.Platform.Infrastructure.Services;
using JGSY.CMS.LowCode.Platform.Application.Interfaces;

namespace JGSY.CMS.LowCode.Platform.Infrastructure.Configuration.ServiceModules.Modules
{
    /// <summary>
    /// 认证和授权服务模块
    /// 包含JWT认证、授权策略等安全相关服务
    /// </summary>
    public class AuthenticationModule : IServiceModule
    {
        public string ModuleName => "认证和授权服务";
        public int Priority => 3;
        public bool LoadInFastMode => true; // 快速模式需要基本认证
        public ModulePermission RequiredPermission => ModulePermission.AuthenticationServices;
        public bool IsCriticalModule => true; // 关键模块

        public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
        {
            // 完整认证功能
            ConfigureJwtAuthentication(services, configuration);
            ConfigureAuthorizationPolicies(services, configuration);
        }

        public void ConfigureMinimalServices(IServiceCollection services, IConfiguration configuration)
        {
            // 精简认证功能 - 只配置基本JWT认证
            var jwtSettings = configuration.GetSection("JWT").Get<JwtSettings>();
            if (jwtSettings != null)
            {
                services.Configure<JwtSettings>(configuration.GetSection("JWT"));
                services.AddScoped<IJwtService, JwtService>();
                
                // 基本JWT认证
                services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                    .AddJwtBearer(options =>
                    {
                        options.TokenValidationParameters = new TokenValidationParameters
                        {
                            ValidateIssuer = true,
                            ValidateAudience = true,
                            ValidateLifetime = true,
                            ValidateIssuerSigningKey = true,
                            ValidIssuer = jwtSettings.Issuer,
                            ValidAudience = jwtSettings.Audience,
                            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.Key))
                        };
                    });
            }
        }

        public bool ValidateConfiguration(IConfiguration configuration)
        {
            var jwtSettings = configuration.GetSection("JWT").Get<JwtSettings>();
            return jwtSettings != null && 
                   !string.IsNullOrEmpty(jwtSettings.Key) && 
                   !string.IsNullOrEmpty(jwtSettings.Issuer) && 
                   !string.IsNullOrEmpty(jwtSettings.Audience);
        }

        private void ConfigureJwtAuthentication(IServiceCollection services, IConfiguration configuration)
        {
            // JWT设置配置
            var jwtSettings = configuration.GetSection("JWT").Get<JwtSettings>();
            if (jwtSettings == null)
            {
                throw new InvalidOperationException("JWT settings not found in configuration");
            }

            services.Configure<JwtSettings>(configuration.GetSection("JWT"));
            services.AddScoped<IJwtService, JwtService>();

            // JWT认证配置
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer = jwtSettings.Issuer,
                    ValidAudience = jwtSettings.Audience,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.Key)),
                    ClockSkew = TimeSpan.Zero
                };

                options.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        context.Response.Headers.Append("Token-Expired", "true");
                        return Task.CompletedTask;
                    }
                };
            });
        }

        private void ConfigureAuthorizationPolicies(IServiceCollection services, IConfiguration configuration)
        {
            // 授权策略配置
            var permissionEnabled = ConfigurationAccessor.PermissionEnabled;
            if (permissionEnabled)
            {
                services.AddAuthorization(options =>
                {
                    options.AddPolicy("AdminOnly", policy => policy.RequireRole("Admin"));
                    options.AddPolicy("UserOnly", policy => policy.RequireRole("User", "Admin"));
                    // 可以在这里添加更多自定义策略
                });
                
                StartupLogger.LogPermissionConfiguration(true, new { Policy = "AdminOnly, UserOnly" });
            }
            else
            {
                StartupLogger.LogPermissionConfiguration(false);
            }
        }
    }
}
